package com.atguigu.edu.realtime.app.dwd.db;

import com.atguigu.edu.realtime.util.MyKafkaUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

public class DwdUserBack {
    public static void main(String[] args) {

        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //1.3 指定表执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 2.检查点相关的设置(略)
        //TODO 3.从kafka的topic_db主题中读取数据 创建动态表
        tableEnv.executeSql(MyKafkaUtil.getStartTopicDDL("dwd_user_back"));

        //TODO 4.过滤出回流用户数据
        Table resultTable = tableEnv.sqlQuery("select \n" +
                "common['uid'] user_id,\n" +
                "common['is_new'] is_new,\n" +
                "ts\n" +
                "from `dwd_traffic_start_log`\n");
        tableEnv.createTemporaryView("result_table", resultTable);

        //TODO 5.创建动态表 和要写入的kafka主题进行映射
        tableEnv.executeSql("create table dwd_user_back(\n" +
                "user_id string,\n" +
                "is_new string,\n" +
                "ts string,\n" +

                "primary key(user_id) not enforced\n" +
                ")" + MyKafkaUtil.getUpsertKafkaDDL("dwd_user_back"));

        //TODO 6.写入
        tableEnv.executeSql("insert into dwd_user_back select * from result_table");

    }
}
